document.getElementById('registerBtn').addEventListener('click', function () {
    const username = document.getElementById('username').value;
    const studentId = document.getElementById('studentId').value;
    const password = document.getElementById('password').value;
    const confirmPassword = document.getElementById('confirmPassword').value;
    const role = document.getElementById('role').value;

    // 简单验证
    if (!username ||!studentId ||!password ||!confirmPassword) {
        showToast('请填写所有必填字段', 'danger');
        return;
    }

    if (password!== confirmPassword) {
        showToast('两次输入的密码不一致', 'danger');
        return;
    }

    // 构造请求数据
    const formData = {
        username,
        studentId,
        password,
        role
    };

    // 显示加载状态
    const btn = this;
    const originalText = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<i class="fa fa-spinner fa-spin mr-3"></i> 正在创建账户...';

    // 发送注册请求
    fetch('/register/check', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    })
       .then(response => {
            if (!response.ok) {
                return response.json().then(errorData => {
                    throw new Error(errorData.message || '注册请求出错');
                });
            }
            return response.json();
        })
       .then(data => {
            showToast(data.message,'success');
            setTimeout(() => {
                window.location.href = "/login";
            }, 2000);
        })
       .catch(error => {
            // 显示具体的错误信息
            showToast(error.message, 'danger');
            console.error('注册错误:', error);
        })
       .finally(() => {
            // 重置按钮状态
            btn.disabled = false;
            btn.innerHTML = originalText;
        });
});

// 显示提示框
function showToast(message, type = 'info') {
    // 移除已有的提示框
    const existingToasts = document.querySelectorAll('.toast');
    existingToasts.forEach(toast => toast.remove());

    const toast = document.createElement('div');
    toast.classList.add('toast', type);
    toast.innerHTML = `
        <div class="flex items-center">
            <i class="fa ${
                type ==='success'? 'fa-check-circle text-xl' :
                type === 'danger'? 'fa-exclamation-circle text-xl' :
                'fa-info-circle text-xl'
            } mr-3"></i>
            <span class="font-medium">${message}</span>
        </div>
    `;

    document.body.appendChild(toast);

    // 触发动画
    setTimeout(() => {
        toast.classList.add('show');
    }, 10);

    // 自动关闭
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            toast.remove();
        }, 300);
    }, 3000);
}